package com.rem.photoablum.service;

import com.rem.photoablum.dao.PhotoDao;
import com.rem.photoablum.model.Album;
import com.rem.photoablum.model.Photo;
import com.rem.photoablum.model.User;
import com.rem.photoablum.utils.PhotoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author remembrance
 * @version 1.0
 * @date 2022/3/6 21:40
 */
@Service
public class PhotoService {
    @Autowired
    private PhotoDao photoDao;

    @Autowired
    private PhotoUtil photoUtil;


    public void addPhoto(Integer pid,String url,Long aid){
        //jpa有问题，主键自增不知道为啥没用，用随机数代替id，有十万分之一率插入失败
        long id = (long) (Math.random()*100000+1);
        photoDao.addPhoto(id,pid,aid,url);
    }

    public void upload(MultipartFile file, Integer userId, Album album) {
        Integer pid = userId;
        String url = photoUtil.upload(file, album);
        Long aid = album.getAid();
        addPhoto(pid,url,aid);
    }

    public String handleFileUpload(HttpServletRequest request,User user){
        return photoUtil.handleFileUpload(request,user);
    }

    public String downloadFile(HttpServletRequest request, HttpServletResponse response,Long id){
        Photo photo = photoDao.findById(id).get();
        String photoPath = photo.getUrl();
        System.out.println(photoPath);
        return photoUtil.downloadFile(request,response,photoPath);
    }

    public String deletePhoto(Long id){
        Photo photo = photoDao.findById(id).get();
        String url = photo.getUrl();
        photoDao.deleteById(id);
        return photoUtil.deletePhoto(url);
    }


    public List<Photo> findAllByPid(Integer pid){
        return photoDao.findAllByPid(pid);
    }

    public List<Photo> findAllByAid(Long aid){
        return photoDao.findAllByAid(aid);
    }

}
